const app = getApp()

Page({
  data: {
    serverHost: app.config.serverHost,
    // 商品数据
    goodsList: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    info:0,
    serverHost: app.config.serverHost
  },
  onLoad(e){
    let appData = app.globalData.goodslist
    let tempData = appData.filter(item=>{
      return item._id == e.id
    })
    tempData[0].shelves_time = tempData[0].shelves_time.split('T')[0]
    this.setData({
      goodsList: tempData
    })
  },
  onShow () {
    this.setData({
      info: wx.getStorageSync('shopping_cart').length
    })
  },
  onUnload() {
    if (!wx.getStorageSync('token') || wx.getStorageSync('shopping_cart').length == 0){
      return
    }
    const model = {
      token: wx.getStorageSync('token'),
      shopping_cart: wx.getStorageSync('shopping_cart')
    }
    app.api.updateData('web/goodscart',model,(res)=>{})
  },
  // 跳转到购物车
  toShoppingCart:function(){
    getApp().globalData._id = this.data.goodsList[0]._id
    wx.switchTab({
      url: '/pages/shoppingCart/index'
    });
  },
  // 添加到购物车
  addCart () {
    if (!wx.getStorageSync('token')) {
      wx.showToast({
        title: '请先登录...',
        image: '../../static/icons/err.png',
        duration: 2000,
        success: function (res) {
          wx.navigateTo({
            url: '../my/loging/index',
          })
        }
      })
      return
    }
    var id = this.data.goodsList[0]._id
    var shopping_cart = wx.getStorageSync('shopping_cart')
    var a = shopping_cart.findIndex(item=>{
      return item.goods == id
    })
    a>=0 ? shopping_cart.splice(a, 1, { goods: id, value: shopping_cart[a].value+1 }) : shopping_cart.push({ goods: id, value: 1 })
    wx.setStorageSync('shopping_cart', shopping_cart)
    this.setData({
      info: wx.getStorageSync('shopping_cart').length
    })
    wx.showToast({
      title: '添加成功~',
      icon: 'success',
      mask: true,
      duration: 1000
    })
  }
})